package com.base.caselib;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.arvin.imagepicker.bean.ImageItem;
import com.base.caselib.bean.CaseBean;
import com.base.caselib.bean.CaseDetailBean;
import com.base.caselib.bean.CheckBoxBean;
import com.base.caselib.bean.DropBean;
import com.base.caselib.bean.ToDoAgreeBean;
import com.base.caselib.databinding.ActivityAdvanceDetailBinding;
import com.base.caselib.presenter.CaseDetailPresenter;
import com.base.caselib.view.CaseDetailView;
import com.base.commonlib.base.BaseApp;
import com.base.commonlib.base.CBaseBarMvpActivity;
import com.base.commonlib.http.RealNetWorkUtil;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zw on 2019/10/18.
 * 先行登记详情
 */
@Route(path = "/case/advance")
public class AdvanceDetailActivity extends CBaseBarMvpActivity<CaseDetailPresenter> implements CaseDetailView {

    private String mStatus = "";//案件状态


    private ToDoAgreeBean mBean = new ToDoAgreeBean();
    private Map<String,Object> mTodoMap = new HashMap<>();
    private String DepertId = "";


    @Autowired(name = "istod")
    boolean isTod;
    @Autowired()
    public String cformId;//表单ID
    @Autowired
    String todoId;
    @Autowired()
    public String id;//案件案件
    @Autowired
    String busId;//流程ID
    @Autowired
    String proId;
    @Autowired
    String applyUserId;
    @Autowired
    String content;
    @Autowired
    String lawType;

    String nextCaseStatus="";//案件下一个状态（字典）

    String nextCaseForId = "";

    List<LinearLayout> mLayout = new ArrayList<>();
    private int formFontSize;
    private ActivityAdvanceDetailBinding mBinding;
    private CaseDetailBean.CaseEvidence caseEvidence;
    private Gson gson = new Gson();
    private List<ImageItem> ls = new ArrayList<>();
    private List<CaseDetailBean.CaseEvidence> caseEvidenceList;


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_advance_detail;
    }


    @Override
    protected void init() {
        super.init();
        ARouter.getInstance().inject(this);
        mBinding = (ActivityAdvanceDetailBinding) mRootBinding;
        setBackNavigation();
        mPresenter = new CaseDetailPresenter(this, this);
        mPresenter.start();
        setRigImg(R.drawable.ic_process, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance().build("/case/caseprocess")
                        .withString("id",id)
                        .navigation();
            }
        });
//        mPresenter.getInfo(todoId);


        mBinding.agree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mBean.setAgree("1");
                mBean.setStatus("3");
                if (TextUtils.isEmpty(mBinding.option.getText().toString().trim())){
                    mBean.setAppContent("建议实施证据先行登记保存。");
                }else {
                    mBean.setAppContent(mBinding.option.getText().toString().trim());
                }
                mPresenter.AgreeOrDis(mBean);
            }
        });
        mBinding.disagree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mBean.setAgree("0");
                mBean.setStatus("1");
                if (TextUtils.isEmpty(mBinding.option.getText().toString().trim())){
                    mBean.setAppContent("不同意");
                }else {
                    mBean.setAppContent(mBinding.option.getText().toString().trim());
                }
                mPresenter.CaseBack(mBean);
            }
        });
        mBinding.caseBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ARouter.getInstance().build("/case/caseedit")
                        .withString("ID","ylp9W4bF9ykafcByq8R")
                        .withInt("num",2)
                        .withString("id",id)
                        .withString("cformId",cformId)
                        .navigation();
            }
        });
        mBean.setBusId(busId);
        mBean.setProId(proId);
        mBean.setBillId(id);
        mBean.setFormId(cformId);
        mBean.setApplyUserId(applyUserId);
        mBean.setContent(content);
//        mBean.setLawType(lawType);
        mBean.setTodoSource("02300003");
        if (RealNetWorkUtil.TYPE.equals("0")){
            mBean.setIsSendSMS(1);
        }else if (RealNetWorkUtil.TYPE.equals("1")){
            mBean.setIsSendSMS(0);
        }else {
            mBean.setIsSendSMS(0);
        }
    }




    @Override
    protected void start() {
        Map<String, String> parmes = new HashMap<>();
        parmes.put("id", id);
        parmes.put("formId", cformId);
        mPresenter.getInfo(parmes,false);
    }

    @Override
    public void returnCaseDetailBean(CaseDetailBean bean) {
        mBean.setTbFlag(bean.getFormMainValue());
        setBarTitle(bean.getFormTitle());
        try {
            formFontSize = (int) (bean.getFormFontSize() * 1.2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (CaseDetailBean.ModulesBean models : bean.getModules()) {
            if (models.getChildValues() != null) {
                for (CaseDetailBean.ModulesBean.ChildValuesBean childValueBean : models.getChildValues()) {
                    if (childValueBean.getPic()!=null){
                        try {
                            caseEvidence = new Gson().fromJson(childValueBean.getPic(), new TypeToken<CaseDetailBean.CaseEvidence>() {
                            }.getType());
                            if (!TextUtils.isEmpty(caseEvidence.getContent())){
                                if (caseEvidence.getContent().startsWith("http")) {
                                    ls.add(new ImageItem(caseEvidence.getContent(), caseEvidence.getName()));
                                }else {
                                    ls.add(new ImageItem(RealNetWorkUtil.getBaseUrl()+"api-file/"+caseEvidence.getContent(), caseEvidence.getName()));
                                }
                            }
                        }catch (JsonSyntaxException e){
                            e.printStackTrace();
                            caseEvidenceList = new Gson().fromJson(childValueBean.getPic(), new TypeToken<List<CaseDetailBean.CaseEvidence>>() {
                            }.getType());
                            for (CaseDetailBean.CaseEvidence it :caseEvidenceList){
                                if (!TextUtils.isEmpty(it.getContent())){
                                    if (it.getContent().startsWith("http")) {
                                        ls.add(new ImageItem(it.getContent(), it.getName()));
                                    }else {
                                        ls.add(new ImageItem(RealNetWorkUtil.getBaseUrl()+"api-file/"+it.getContent(), it.getName()));
                                    }
                                }
                            }
                        }
                    }

                }

                mBinding.pick.setPics(ls);
            }
            if (models.getChildName().equals("t_Withholding_items")){
                String goods="";
                //物品情况
                for (CaseDetailBean.ModulesBean.ChildValuesBean row : models.getChildValues()) {
                        goods+="物品名称:"+row.getItem_name()+"\n";
                        goods+="车牌号码:"+row.getLicense_number()+"\n";
                        goods+="物品数量:"+row.getItem_amount()+"\n\n";
                }
                mBinding.caseZhanyao.setText(goods);
            }

            for (CaseBean.ModulesBean.RowsBean row : models.getRows()) {
                if (row.getFieldSave().equals("register_date")) {
                    mBean.setUpdateDate(row.getValue());
                    mTodoMap.put("registerDate","Date");
                }
//                if (row.getFieldSave().equals("closureDate")){
//                    mTodoMap.put("closureDate",row.getValue());
//                }
                if (row.getFieldSave().equals("status")){
                    mTodoMap.put("status","3");
                }
                if (row.getFieldSave().equals("lawType")){
                    mTodoMap.put("lawType",row.getValue());
                }
//                if (row.getFieldSave().equals("registerDate")){
//                    mTodoMap.put("registerDate",row.getValue());
//                }
                if (row.getFieldSave().equals("law_enforcing_department_name2")){
                    createRow(row,mBinding.tvDept);
                }else if (row.getFieldSave().equals("modelid")){
                    if (row.getValue()!=null&&row.getValue().equals("y7RgLtwaDqfpJr0j1gD")){
                        mBean.setModelId("");
                    }else {
                        mBean.setModelId(row.getFixValue());
                    }
                }else if (row.getFieldSave().equals("law_enforcing_member_name1")||row.getFieldSave().equals("law_enforcing_member_name2")){

                    //获取联动数据
                    //获取联动数据
                    Map<String,String> parmes = new HashMap<>();
                    parmes.put("dropValue",row.getSelectFieldValue());
                    parmes.put("dropLabel",row.getSelectFieldLabel());
                    parmes.put("dropTable",row.getSelectTableValue());
                    parmes.put("dropConditionFormula",row.getDropFunction());
                    List<DropBean> list = new Gson().fromJson(row.getDropJsonArr(),new TypeToken<List<DropBean>>(){}.getType());
                    for (DropBean dropBean : list){
                        if (dropBean.getDropField().equals("dept_id")) {
                            if (dropBean.getRank().equals("02200001")) {
                                for (CaseBean.ModulesBean.RowsBean rosw : models.getRows()) {
                                    if (rosw.getFieldSave().equals("law_enforcing_department_name2")){
                                        dropBean.setValue(rosw.getValue());
                                    }
                                }
                            }
                        }
                    }
                    parmes.put("dropConditionFormula",row.getDropFunction());
                    parmes.put("dropConditionJson",new Gson().toJson(list));
                    mPresenter.getFieldValue(parmes,row.getValue(),mBinding.tvMember);


                }else if (row.getFieldSave().equals("investigate_punish_datetime")){
                    createRow(row,mBinding.tvDate);
                }else if (row.getFieldSave().equals("litigant_citizen_name")||row.getFieldSave().equals("litigant_org_name")){
                    if (TextUtils.isEmpty(mBinding.tvTarget.getText().toString())) {
                        createRow(row, mBinding.tvTarget);
                    }
                }else if (row.getFieldSave().equals("case_summary")){
                    createRow(row,mBinding.caseZhanyao);
                }
            }
            if (isTod) {
                for (CaseBean.ModulesBean.RowsBean row : models.getRows()) {
                    if (row.getFieldSave().equals("status")) {
                        mStatus = row.getFixValue();
                        initStates();
                    }else if (row.getFieldSave().equals("case_status")){

                    }else if (row.getFieldSave().equals("next_case_status")){
                        nextCaseStatus = row.getFixValue();
                        mBean.setNextCaseStatus(nextCaseStatus);
                        mBean.setCaseStatus(nextCaseStatus);
                    }
                }
            }
        }
//        if (isTod){
//            Map<String, String> parmes = new HashMap<>();
//            parmes.put("id", id);
//            parmes.put("cformId", nextCaseForId);
//            mPresenter.getInfo(parmes,true);
//        }
        mTodoMap.put("caseStatus","02620001");
        mBean.setParam(mTodoMap);
    }

    @Override
    public void returnNextCaseDetailBean(CaseDetailBean bean) {

        for (CaseDetailBean.ModulesBean models : bean.getModules()) {
            for (CaseBean.ModulesBean.RowsBean row : models.getRows()) {
                if (row.getFieldSave().equals("next_form_id")){
                    mBean.setNextCFormId(row.getFieldSave());
                }
            }
        }
    }

    @Override
    public void returnPersion(String name) {
        if (TextUtils.isEmpty(mBinding.tvMember.getText().toString())) {
            mBinding.tvMember.setText(name == null ? "" : name);
        }else {
            mBinding.tvMember.setText(mBinding.tvMember.getText().toString().trim() +","+(name == null ? "" : name));
        }
    }

    @Override
    public void returnLawType(String lawType) {
        this.lawType = lawType;
    }

    private void initStates(){
        mBinding.llApprove.setVisibility(View.VISIBLE);
        if (mStatus.equals("4")){
            mBinding.caseBack.setVisibility(View.VISIBLE);
            mBinding.agree.setVisibility(View.GONE);
            mBinding.disagree.setVisibility(View.GONE);
        }else {
            mBinding.caseBack.setVisibility(View.GONE);
            mBinding.agree.setVisibility(View.VISIBLE);
            mBinding.disagree.setVisibility(View.VISIBLE);
        }
    }




    private void createRow(final CaseBean.ModulesBean.RowsBean row, TextView textView){
        if (row.getFieldSave().equals("law_enforcing_department_name2")){
            //获取联动数据
            //获取联动数据
            Map<String,String> parmes = new HashMap<>();
            parmes.put("dropValue",row.getSelectFieldValue());
            parmes.put("dropLabel",row.getSelectFieldLabel());
            parmes.put("dropTable",row.getSelectTableValue());
            parmes.put("dropConditionFormula",row.getDropFunction());
            List<DropBean> list = new Gson().fromJson(row.getDropJsonArr(),new TypeToken<List<DropBean>>(){}.getType());
            for (DropBean dropBean : list){
                if (dropBean.getRank().equals("02200001")){
                    dropBean.setValue(BaseApp.getUser().getCompanyId());
                }
            }
            parmes.put("dropConditionFormula",row.getDropFunction());
            parmes.put("dropConditionJson",new Gson().toJson(list));

            mPresenter.getFieldValue(parmes,row.getValue(),textView);
        }else{
            if (TextUtils.isEmpty(textView.getText().toString())) {
                textView.setText(row.getValue() == null ? "" : row.getValue());
            }else {
                textView.setText(textView.getText().toString().trim() +","+(row.getValue() == null ? "" : row.getValue()));
            }
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter!=null){
            mPresenter.release();
        }
    }
}
